﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using ScrumPilot.Domain.Helpers;
using ScrumPilot.Domain.Models;
using ScrumPilot.TFSHelpers;

namespace ScrumPilot.Domain.BPL
{
    public class UserStoriesServices : BusinessProcessLayer
    {
        public UserStoriesServices(TFSServices tfs)
            : base(tfs)
        {
        }

        public List<UserStoryProject> GetUserStoriesInSprint(Int32 userId, string tfsRootUrl)
        {
            List<UserStoryProject> lstRet = null;
            this.CurrentUserID = userId;
            var selectedProjects = this.CurrentSprintsProjectIDDictonary();
            if (selectedProjects != null)
            {
                this.GetAllUserStory();

                if (this.WorkItemsList != null)
                {
                    // var status = new[] { WorkItemState.Todo, WorkItemState.InProgress, WorkItemState.ToTest, WorkItemState.Done };
                    var lstWie = new ConcurrentBag<UserStory>(WorkItemsList.Select(workItem => workItem.CastTFSWorkItem<UserStory>(TFS, "", false, true)));
                    using (var unitOfWork = new UnitOfWork())
                    {
                        lstRet = selectedProjects.Select(project =>
                                                             {
                                                                 var prj =
                                                                     unitOfWork.ProjectRepository.GetById(project.Key);

                                                                 var ust =
                                                                     lstWie.AsParallel()
                                                                           .WithDegreeOfParallelism(2)
                                                                           .Where(p => p.ProjectID == project.Key)
                                                                           .OrderBy(p => p.StackRank)
                                                                           .ThenBy(p => p.ID);

                                                                 ust.ForAll(p =>
                                                                                {
                                                                                    p.Url = String.Format(p.Url,
                                                                                                          tfsRootUrl);
                                                                                });

                                                                 UserStoryProject usp = null;
                                                                 if (prj != null)
                                                                 {
                                                                     if (ust.Any())
                                                                     {
                                                                         usp = new UserStoryProject
                                                                               {
                                                                                   ID = project.Key,
                                                                                   Name = prj.name,
                                                                                   CurrentSprint = prj.currentsprint,
                                                                                   UserStories = ust.ToList(),
                                                                                   TotalTasks = ust.Count(),
                                                                                   // TotalScore = ust.Sum(p => p.Score),
                                                                                   TotalCompletedTime =
                                                                                       ust.Sum(p => p.CompletedTime),
                                                                                   TotalRemainTime =
                                                                                       ust.Sum(p => p.RemainTime),
                                                                                   TotalEstimatedTime =
                                                                                       ust.Sum(p => p.EstimatedTime),
                                                                                   RatioCompleted =
                                                                                       (int)
                                                                                       ust.Average(p => p.RatioCompleted)
                                                                               };

                                                                     }
                                                                     else
                                                                     {
                                                                         usp = new UserStoryProject
                                                                         {
                                                                             ID = project.Key,
                                                                             Name = prj.name,
                                                                             CurrentSprint = prj.currentsprint
                                                                         };
                                                                     }
                                                                 }
                                                                 return usp;
                                                             }).ToList();
                    }
                }
            }
            return lstRet;
        }

        private void GetAllUserStory()
        {
            var qry = new TFSQuery(TFS.TfsWorkItemStore);
            // Get all workitems using in dashboard
            this.WorkItemsList = qry.GetWorkItemList(this.CurrentSprintsDictonary,
                                                           new List<string> { "User Story" }, null, false, false);
        }
    }
}
